/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 *         
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. Unless required by applicable law or
 * agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.rhok.ncn.application;

import java.util.List;

import org.rhok.ncn.R;
import org.rhok.ncn.background.TrackingService;
import org.rhok.ncn.common.CommonData;
import org.rhok.ncn.common.Utils;
import org.rhok.ncn.datatypes.LocationData;
import org.rhok.ncn.datatypes.MapOverlay;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class NCNMainActivity extends MapActivity {
	private EditText gpsText;
	private EditText signalText;
	private EditText wifiText;
	private ImageButton zoomToBtn;
	private LinearLayout dataView;
	
	private MapController mapController;
	private MapView mapView;
	private MyLocationOverlay locOverlay;
	
    public Drawable greenDrawable;
    public Drawable yellowDrawable;
    public Drawable redDrawable;

	private List<Overlay> overlays;
	
	@Override
	public void onCreate(Bundle savedInstanceStage) {
		super.onCreate(savedInstanceStage);
		setContentView(R.layout.map_layout);
		
        greenDrawable = getResources().getDrawable(R.drawable.greendot);
        yellowDrawable = getResources().getDrawable(R.drawable.yellowdot);
        redDrawable = getResources().getDrawable(R.drawable.reddot);
        getViews();
		
        Handler handler = new Handler() {
            @SuppressWarnings("unchecked")
            @Override
            public void handleMessage(Message msg) {
                List<LocationData> locs = (List<LocationData>) msg.obj;
                List<Overlay> overlays = ((MapView) findViewById(R.id.map_view)).getOverlays();
                
                if (msg.obj != null) {
	                for (LocationData loc : locs) {
	                    GeoPoint point = new GeoPoint((int) (loc.lat() * 1E6), (int) (loc.lng() * 1E6));
	                    OverlayItem item = new OverlayItem(point, "", "");
	
	                	MapOverlay overlay;
	                    if (loc.signal() < 2) {
	                        overlay = new MapOverlay(redDrawable);
	                    } else if (loc.signal() < 4) {
	                        overlay = new MapOverlay(yellowDrawable);
	                    } else {
	                        overlay = new MapOverlay(greenDrawable);
	                    }
	
	                    overlay.addOverlay(item);
	                    overlays.add(overlay);
	                    
	                    gpsText.setText(loc.lat() + ", " + loc.lng());
	
	                }
                }
                
                wifiText.setText(CommonData.wifiStrength + "");
                signalText.setText(CommonData.signalStrength + "");

                msg.obj = null;
            }
        };

        CommonData.setFields(this, handler);
        startService(new Intent(this, TrackingService.class));
		
		setupMap();
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    CommonData.isActivityRunning = true;
	    List<Overlay> overlays = ((MapView) findViewById(R.id.map_view)).getOverlays();
	    overlays.clear();
        Utils.populateOverlays();
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    CommonData.isActivityRunning = false;
	}
	
	private void getViews() {
		gpsText = (EditText) findViewById(R.id.value_gps);
		signalText = (EditText) findViewById(R.id.value_signal);
		wifiText = (EditText) findViewById(R.id.value_wifi);
		
		mapView = (MapView) findViewById(R.id.map_view);
		dataView = (LinearLayout) findViewById(R.id.data_view);
		zoomToBtn = (ImageButton) findViewById(R.id.my_loc_button);
		zoomToBtn.setImageResource(android.R.drawable.ic_menu_mylocation);
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
    /* (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu:
            swapViews(item);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	
	private void setupMap() {
		mapView.computeScroll();
		mapView.setBuiltInZoomControls(true);
		mapController = mapView.getController();
		overlays = mapView.getOverlays();
		
		// Add the current location marker
		locOverlay = new MyLocationOverlay(this, mapView);
		locOverlay.enableCompass();
		locOverlay.enableMyLocation();
		locOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				mapController.animateTo(locOverlay.getMyLocation());
			}
		});
		overlays.add(locOverlay);
	}
	
	/**
	 * Zooms to the current location, if one exists.
	 * @param view the current view, supplied by the system
	 */
	public void zoomToLoc(View view) {
		GeoPoint currentLoc = locOverlay.getMyLocation();
		if (currentLoc != null) {
			mapController.animateTo(currentLoc);
			mapController.setZoom(17);
		} else {
			Utils.toast(this, "No location found. Please make sure your GPS is activated.");
		}
	}

	private void swapViews(MenuItem selected) {
		dataView = (LinearLayout) findViewById(R.id.data_view);
		if (dataView.getVisibility() == LinearLayout.VISIBLE) {
			dataView.setVisibility(LinearLayout.GONE);
			mapView.setVisibility(MapView.VISIBLE);
			zoomToBtn.setVisibility(ImageButton.VISIBLE);
			selected.setTitle(R.string.view_data);
		} else {
			dataView.setVisibility(LinearLayout.VISIBLE);
			mapView.setVisibility(MapView.GONE);
			zoomToBtn.setVisibility(ImageButton.GONE);
			selected.setTitle(R.string.view_map);
		}
	}
	
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            Utils.displayQuitDialog(this);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
